<template>
  <div class="app-container">
    <!--搜索条件输入表单-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="所属景区" prop="scenicId" label-width="80px">
        <treeselect v-model="queryParams.scenicId" :options="scenicOptions" :show-count="true"
                    @open="treeselectOpen"
                    @close="treeselectClose"
                    @select="treeselectSelected"
                    @deselect="treeselectDeselect"
                    @input="treeselectInput"
                    :clearable="true"
                    placeholder="请选择归属景区"/>
      </el-form-item>
      <el-form-item label="所属码头" prop="wharfId" label-width="80px">
        <el-select v-model="queryParams.wharfId" placeholder="所属码头">
          <el-option v-for="wharf in wharfOptions" :key="wharf.wharfId" :label="wharf.wharfName"
                     :value="wharf.wharfId"></el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="码头名称" prop="wharfName" label-width="100px">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.wharfName"-->
      <!--          placeholder="请输入码头的名称"-->
      <!--          clearable-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label-width="120px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!--操作按钮区-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:fence:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdateFence"
          v-hasPermi="['system:fence:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:fence:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['system:fence:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getFenceList"></right-toolbar>
    </el-row>
    <!--搜索结果列表区-->
    <el-table v-loading="loading" :data="fenceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="电子围栏ID" align="center" prop="fenceId" width="100"/>
      <el-table-column label="所属景区" align="center" prop="scenicName"/>
      <el-table-column label="所属码头" align="center" prop="wharfName" width="150"/>
      <el-table-column key="status" prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="绿区安全距离(米)" align="center" prop="greenDistance" width="120"/>
      <el-table-column label="黄区安全距离(米)" align="center" prop="yellowDistance" width="120"/>
      <el-table-column label="坐标点个数" align="center" prop="coordinateNum" width="120"/>
      <el-table-column label="坐标信息" align="center" prop="coordinates"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="更新时间" align="center" prop="updateTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateFence(scope.row)"
            v-hasPermi="['system:fence:edit']"
          >编辑
          </el-button>
          <!--          <router-link to="/system/fenceEdit/index" class="link-type">-->
          <!--            <span>编辑</span>-->
          <!--          </router-link>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:fence:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getFenceList"
    />

    <!-- 添加或修改电子围栏对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false"
               :close-on-press-escape="false">
      <!--      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="left">-->
      <el-form ref="form" :model="form" label-width="130px" label-position="left">
        <el-form-item
          label="所属景区"
          prop="scenicId"
          :rules="{
                  required: true, message: '所属景区不能为空', trigger: 'blur'
          }"
        >
          <treeselect v-model="form.scenicId" :options="scenicOptions" :show-count="true" @input="treeselectInput"
                      placeholder="请选择归属景区" :disabled="isTreeSelectDisabled"/>
        </el-form-item>
        <el-form-item
          label="所属码头"
          prop="wharfId"
          :rules="{
                  required: true, message: '所属码头不能为空', trigger: 'blur'
          }"
        >
          <el-select v-model="form.wharfId" placeholder="所属码头" :disabled="isTreeSelectDisabled">
            <el-option v-for="wharf in wharfOptions" :key="wharf.wharfId" :label="wharf.wharfName"
                       :value="wharf.wharfId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="绿区安全距离(米)"
          prop="greenDistance"
        >
          <el-input v-model="form.greenDistance" placeholder="绿区安全距离(米)" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item
          label="黄区安全距离(米)"
          prop="yellowDistance"
        >
          <el-input v-model="form.yellowDistance" placeholder="黄区安全距离(米)" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="状态" required>
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item-->
        <!--          v-for="(coordinate, index) in form.coordinates"-->
        <!--          :label="'坐标' + (index+1)"-->
        <!--          :key="coordinate.key"-->
        <!--          :prop="'coordinates.' + index + '.value'"-->
        <!--          :rules="{-->
        <!--              required: true, message: '坐标不能为空', trigger: 'blur'-->
        <!--           }"-->
        <!--          label-width="80px"-->
        <!--        >-->
        <el-form-item
          v-for="(coordinate, index) in form.coordinates"
          :label="'坐标' + (index+1)"
          :key="index"
          label-width="80px"
          required
        >
          <el-col :span="9">
            <!--此处prop属性必须设置，否则校验会不生效-->
            <el-form-item
              :prop="'coordinates.' + index + '.lon'"
              :rules="{
                  required: true, message: '域名不能为空', trigger: 'blur'
              }"
            >
              <el-input v-model="coordinate.lon" placeholder="经度" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1" style="margin-left: 10px">-</el-col>
          <el-col :span="9">
            <el-form-item
              :prop="'coordinates.' + index + '.lat'"
              :rules="{
                  required: true, message: '域名不能为空', trigger: 'blur'
              }"
            >
              <el-input v-model="coordinate.lat" placeholder="纬度" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button @click.prevent="removeDomain(coordinate)" style="margin-left: 10px">删除</el-button>
          </el-col>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCoordinate" type="success" plain>新增坐标</el-button>
        <el-button type="primary" @click="submitForm" style="margin-left: 100px">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addFence, delFence, getFence, listFence, updateFence} from "@/api/system/fence";
import {scenicTreeSelect} from "@/api/system/user";
import {getWharfListByScenicId} from "@/api/system/wharf";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Fence",
  components: {
    Treeselect
  },
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电子围栏表格数据
      fenceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否禁用treeselect
      isTreeSelectDisabled: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        scenicId: undefined,
        wharfId: undefined
      },
      // 表单参数
      form: {
        fenceId: undefined,
        scenicId: undefined,
        wharfId: undefined,
        status: "0",
        greenDistance: undefined,
        yellowDistance: undefined,
        coordinates: [{
          lon: '',
          lat: '',
          key: Date.now()
        }]
      },
      // 表单校验
      rules: {
        scenicId: [
          {required: true, message: '所属景区不能为空', trigger: 'blur'}
        ],
        wharfId: [
          {required: true, message: '所属码头不能为空', trigger: 'blur'}
        ],
        // coordinates: {
        //   lon: [
        //     {required: true, message: '经度值不能为空', trigger: 'blur'}
        //   ],
        //   lat: [
        //     {required: true, message: '纬度值不能为空', trigger: 'blur'}
        //   ]
        // }

      },
      // 景区树选项
      scenicOptions: [],
      // 码头数组
      wharfOptions: [],
      scenicName: '',
      defaultProps: {
        children: "children",
        label: "label"
      },
    };
  },
  created() {
    /** 查询电子围栏列表 */
    this.getFenceList();

    /** 查询景区下拉树结构 */
    this.getScenicTree();
  },
  methods: {
    /** 查询电子围栏列表 */
    getFenceList() {
      this.loading = true;
      listFence(this.queryParams).then(res => {
        this.fenceList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 查询景区下拉树结构 */
    getScenicTree() {
      scenicTreeSelect().then(res => {
        this.scenicOptions = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fenceId: undefined,
        scenicId: undefined,
        wharfId: undefined,
        status: "0",
        coordinates: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getFenceList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fenceId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.coordinates = [
        {
          lon: '',
          lat: ''
        }
      ]

      this.open = true;
      this.title = "添加电子围栏";
      this.isTreeSelectDisabled = false;
    },
    /** 修改按钮操作 */
    handleUpdateFence(row) {
      console.log("handleUpdateFence row: ", row)
      this.reset();
      this.open = true;
      this.title = "修改电子围栏";
      this.isTreeSelectDisabled = true;

      const fenceId = row.fenceId || this.ids
      getFence(fenceId).then(res => {
        let data = res.data;
        this.form.fenceId = data.fenceId;
        this.form.scenicId = data.scenicId;
        this.form.wharfId = data.wharfId;
        this.form.status = data.status;
        this.form.greenDistance = data.greenDistance;
        this.form.yellowDistance = data.yellowDistance;
        let coordinateArr = data.coordinates.split(",");
        for (let i = 0; i < coordinateArr.length / 2; i++) {
          this.form.coordinates.push({
            lon: coordinateArr[i * 2],
            lat: coordinateArr[i * 2 + 1]
          })
        }
        getWharfListByScenicId(data.scenicId).then(res => {
          this.wharfOptions = res.data;
        })
      });

      // this.$router.push({
      //   path: "/system/fenceEdit/index"
      // })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // console.log("submitForm: this.form= ", this.form)
          let coordinatesArr = [];
          this.form.coordinates.forEach((coordinate, index) => {
            coordinatesArr.push(coordinate.lon);
            coordinatesArr.push(coordinate.lat);
          })

          let requestData = {
            fenceId: this.form.fenceId,
            scenicId: this.form.scenicId,
            wharfId: this.form.wharfId,
            status: this.form.status,
            coordinates: coordinatesArr.join(","),
            greenDistance: this.form.greenDistance,
            yellowDistance: this.form.yellowDistance
          }
          // console.log("requestData: ", requestData)
          if (this.form.fenceId != null) {
            updateFence(requestData).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getFenceList();
            });
          } else {
            addFence(requestData).then(res => {
              this.$modal.msgSuccess("新增成功");
            }).catch(err => {
              this.$modal.msgError("新增失败");
            }).finally(() => {
              this.open = false;
              this.getFenceList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const electronicFenceIds = row.fenceId || this.ids;
      this.$modal.confirm('是否确认删除电子围栏编号为"' + electronicFenceIds + '"的数据项？').then(function () {
        return delFence(row.scenicId, electronicFenceIds);
      }).then(() => {
        this.getFenceList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/fence/export', {
        ...this.queryParams
      }, `fence_${new Date().getTime()}.xlsx`)
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      // this.queryParams.deptId = data.id;
      this.queryParams.scenicId = data.id;
      this.handleQuery();
    },
    removeDomain(coordinate) {
      var index = this.form.coordinates.indexOf(coordinate)
      if (index !== -1) {
        this.form.coordinates.splice(index, 1)
      }
    },
    addCoordinate() {
      this.form.coordinates.push({
        lon: '',
        lat: ''
      });
    },
    treeselectSelected(node, instanceId) {
      // console.log('treeselectSelected:', node, instanceId);
    },
    treeselectDeselect() {
      // console.log("treeselectDeselect execute.")
    },
    treeselectInput(value, instanceId) {
      // console.log("treeselectInput execute. ", value, instanceId)
      if (value) {
        getWharfListByScenicId(value).then(res => {
          // console.log("getWharfListByScenicId res.data: ", res.data)
          this.wharfOptions = res.data;
        })
      } else {
        this.wharfOptions = []
        this.resetForm("queryForm");

        this.form.wharfId = '';
      }
    },
    treeselectOpen(instanceId) {
      // console.log("treeselectOpen, ", instanceId)
    },
    treeselectClose(value, instanceId) {
      // console.log("treeselectClose, ", value, instanceId)
    },

  }
};
</script>

<style scoped>
.el-form-item__content button:nth-child(1) {
  margin-left: 15px;
}

/*.el-form-item__content .vue-treeselect {*/
/*  display: inline-block;*/
/*}*/

.el-form--inline {
  margin-bottom: 20px;
}

>>> .vue-treeselect__control {
  width: 260px;
}


</style>
